package gnss

import (
	"dgo/goutils/dnet"
	"dgo/goutils/utils"
	"log"
)

type EventNtripServerBuffer func(sender *NtripServer, buffer []byte)
type NtripServer struct {
	TcpClient       *dnet.ASyncTcpClient
	RemoteAddress   string
	MountPoint      string
	Pass            string
	state           int
	authstr         string
	postHeader      []byte
	eventRecvBuffer *EventNtripServerBuffer
}

func NewNtripServer() *NtripServer {
	rval := &NtripServer{
		TcpClient: dnet.NewASyncTcpClient(),
	}
	rval.TcpClient.OnDisconnected = rval.onDisconnected
	rval.TcpClient.OnConnected = rval.onConnected
	rval.TcpClient.OnRecvBuffer = rval.onRecvBuffer
	return rval
}

func (this *NtripServer) SetOnRecvBuffer(event EventNtripServerBuffer) {
	this.eventRecvBuffer = &event
}

func (this *NtripServer) SetRemoteAddress(addr string) {
	this.RemoteAddress = addr
}

func (this *NtripServer) SetRequestMountPoint(val string) {
	this.MountPoint = val
}

func (this *NtripServer) SetNtripServerAuth(val string) {
	this.authstr = val
}

func (this *NtripServer) onRecvBuffer(sender *dnet.ASyncTcpClient, buffer []byte) {
	//log.Println(sender.conn.RemoteAddr().StatusString(), "接受到数据:", len(buffer))
	if this.state == 0 {
		utils.Log.Debug(string(buffer))
		this.state = 1
	}
	if this.eventRecvBuffer != nil {
		(*this.eventRecvBuffer)(this, buffer)
	}
}

func (this *NtripServer) onConnected(sender *dnet.ASyncTcpClient) {
	log.Println(sender.Conn.RemoteAddr().String(), "连接成功!")
	this.state = 0
	this.TcpClient.PostSendBuffer(this.postHeader)
	utils.Log.Debug(string(this.postHeader))
}

func (this *NtripServer) onDisconnected(sender *dnet.ASyncTcpClient) {
	utils.Log.Debug(sender.Conn.RemoteAddr().String(), "连接断开!")
}

// 重新加载配置
func (this *NtripServer) Reload() {
	str := "SOURCE " + this.authstr + " /" + this.MountPoint + "\r\n"
	str += "User-Agent:NTRIP DNtripServer/1.0.1\r\n"
	str += "\r\n"
	this.postHeader = []byte(str)
}

func (this *NtripServer) Open() {
	this.Reload()
	this.TcpClient.SetAddress(this.RemoteAddress)
	this.TcpClient.Start()
}

func (this *NtripServer) Close() {
	this.TcpClient.Stop()
}
